#!/usr/bin/env python
import logging
import argparse
import os
import signal
import sys
import datetime
from opslog.cli import settings
from opslog.cli import api
from opslog.cli.client import Client
from opslog.cli.plugins.updater import Updater
from opslog.cli.plugins.log import Log
from opslog.cli.plugins.auth import Auth

DEFAULT_API = "http://opslognet.appspot.com/api/"
INFO_FORMAT = '%(message)s'
DEBUG_FORMAT = '%(asctime)s :  %(message)s'


def sig_handler(signal,frame):
    print "Signal received: %s" % str(signal)
    sys.exit(0)

signal.signal(signal.SIGINT, sig_handler)
signal.signal(signal.SIGTERM, sig_handler)


    
# Main code
def auth_setup(client):
    client.auth_setup()

def auth_check(client):
    client.auth_check()

def auth_forget(client):
    client.auth_forget()

def process(func):
    try:
        func()
    except api.InteractiveAuthRequired,e:
        print "Interactive authentication required.Run opslog with 'auth setup' parameters" 


def main():
    # Setup version info
    version = "dev"
    if os.environ.has_key("OPSLOG_VERSION"):
        version = os.environ["OPSLOG_VERSION"]

    # Init plugins
    log = Log()
    updater = Updater()
    auth = Auth()

    # Setup argument parser
    root_parser = argparse.ArgumentParser(description='Opslog CLI tool')
    root_parser.add_argument("-a", "--api-url", help="Opslog API url (default=%(default)s)", default=DEFAULT_API)
    root_parser.add_argument("-v", "--version",help="Print version",action='version',version='%(prog)s ' +  version)
    root_parser.add_argument("-d","--debug",default=False,action="store_true",help="Enable debug output")
    root_parser.add_argument("-s","--script",default=False,action="store_true",help="Enable script mode (removes misc info like updates,etc..)")
    root_subparsers = root_parser.add_subparsers(help='Core subcommands')
    
    
    # Setup plugins argument parser
    log.setup_arguments(root_subparsers)
    updater.setup_arguments(root_subparsers)
    auth.setup_arguments(root_subparsers)

    # Parse args
    args = root_parser.parse_args()
    
    # Setup logging
    if args.debug:
        logging.basicConfig(level=logging.DEBUG,format=DEBUG_FORMAT)
    else:
        logging.basicConfig(level=logging.INFO,format=INFO_FORMAT)
    
    #Initialize internal services
    server = api.APIProxy(args.api_url)
    client = Client(server,args)
    
    # Initialize plugins
    log.start(client)
    updater.start(client)
    auth.start(client)

    # Run selected task
    process(args.run)

if __name__ == '__main__':
    main()
